package com.zj.leetcode.easy;

/**
 * @program: algorithm
 * @description: 二进制求和
 * 67 add-binary
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class AddBinary {
    public static void main(String[] args) {
//        String a = "1", b = "1100";
        String a = "1010", b = "1011";
        Solution solution = new AddBinary().new Solution();
        System.out.println(solution.addBinary(a, b));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String addBinary(String a, String b) {

            StringBuffer ret = new StringBuffer();
            int carryBit = 0;
            int i = a.length() - 1;
            int j = b.length() - 1;
            while (i >= 0 && j >= 0) {
                int num = Character.getNumericValue(a.charAt(i)) +
                        Character.getNumericValue(b.charAt(j)) +
                        carryBit;
                if (num == 3) {
                    carryBit = 1;
                    ret.append("1");
                } else if (num == 2) {
                    carryBit = 1;
                    ret.append("0");
                } else {
                    carryBit = 0;
                    ret.append(num + "");
                }
                i--;
                j--;
            }

            while (i >= 0) {
                int num = Character.getNumericValue(a.charAt(i)) + carryBit;
                if (num == 2) {
                    carryBit = 1;
                    ret.append("0");
                } else {
                    carryBit = 0;
                    ret.append(num + "");
                }
                i--;
            }
            while (j >= 0) {
                int num = Character.getNumericValue(b.charAt(j)) + carryBit;
                if (num == 2) {
                    carryBit = 1;
                    ret.append("0");
                } else {
                    carryBit = 0;
                    ret.append(num + 0);
                }
                j--;
            }
            if (carryBit != 0) {
                ret.append(1);
            }
            char[] chars = ret.toString().toCharArray();
            this.overTurn(chars);

            return String.valueOf(chars);
        }

        public void overTurn(char[] chars) {
            int head = 0;
            int tail = chars.length - 1;
            while (head < tail) {
                chars[head] ^= chars[tail];
                chars[tail] ^= chars[head];
                chars[head] ^= chars[tail];
                head++;
                tail--;
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}